<?php

/**
 *
 * @filename 财务管理
 */

namespace app\admin\controller;


use think\Controller;
use app\admin\model\Member as Members;
use app\admin\model\Recharge;
use app\admin\model\Getcash;
use app\admin\model\Putlog;
use app\admin\model\Project;
use app\admin\model\Order;
use app\admin\model\OrderProfit;
use app\admin\model\User;
use app\admin\model\OrderPayment;
use app\admin\model\AddAnotherMoneyInfo;
use app\admin\model\GetCompanyData;
use app\admin\model\SubAccount;
use think\Db;
use expand\Yunst;

class Money extends Common {

    private $cModel;   //当前控制器关联模型
    private $rModel;   //当前控制器关联模型
    private $gModel;   //当前控制器关联模型


    public function _initialize() {
        parent::_initialize();
        $this->cModel = new Members;   //别名：避免与控制名冲突
        $this->rModel = new Recharge;   //别名：避免与控制名冲突
        $this->gModel = new Getcash;   //别名：避免与控制名冲突
        $this->pModel = new OrderProfit;
    }

    public function recharge() {
        $where = [];
        if (isset($_GET['status']) && input('get.status') != -1) {  //状态
            $where['g.status'] = ['eq', input('get.status')];
        }
        if (input('get.type')) {
            $where['g.type'] = ['eq', input('get.type')]; //类型
        }

        if (input('get.start_date') && input('get.end_date')) { // 开始/结束同时存在
            $start_date = input('get.start_date') . ' 00:00:00';
            $end_date = input('get.end_date') . ' 23:59:59';
            $where['g.date'] = ['between time', [strtotime($start_date), strtotime($end_date)]];
        }
        if (input('get.search')) {
            $where['m.username|g.mobile'] = ['like', '%' . trim(input('get.search')) . '%'];
        }
        if (input('get._sort')) {
            $order = explode(',', input('get._sort'));
            $order = 'g.' . $order[0] . ' ' . $order[1];
        } else {
            $order = 'g.id desc';
        }
        //导出
        if (input('get.down')) {
            $tableHeader = ['姓名', '手机号', '金额', '余额', '订单号', '创建时间', '类型', '状态', '银行卡类型', '银行卡号'];
            $dataList = $this->rModel
                    ->field('g.*,m.username,m.money as money2')
                    ->alias('g')
                    ->join('tf_member m', 'g.user_id=m.id', 'LEFT')
                    ->where($where)
                    ->order($order)
                    ->select();
            $data = [];
            foreach ($dataList as $k => $v) {
                $data[$k]['username'] = $v['username'];
                $data[$k]['mobile'] = $v['mobile'];
                $data[$k]['money'] = $v['money'];
                $data[$k]['money2'] = $v['money2'];
                $data[$k]['order'] = $v['order'];
                $data[$k]['date'] = $v['date'];
                if ($v['type'] == 1) {
                    $data[$k]['type'] = '网银';
                } elseif ($v['type'] == 2) {
                    $data[$k]['type'] = '快捷';
                }
                if ($v['status'] == 0) {
                    $data[$k]['status'] = '失败';
                } elseif ($v['status'] == 1) {
                    $data[$k]['status'] = '进行中';
                } elseif ($v['status'] == 2) {
                    $data[$k]['status'] = '成功';
                }
                if ($v['iscvv'] == 2) {
                    $data[$k]['iscvv'] = '信用卡';
                } elseif ($v['iscvv'] == 1) {
                    $data[$k]['iscvv'] = '银行卡';
                } else {
                    $data[$k]['iscvv'] = '其他类型';
                }
                $data[$k]['bankcard'] = "\t" . $v['bankcard'];
            }
            ToPHPEXECL($tableHeader, $data, '充值记录');
        }
        $dataList = $this->rModel
                ->field('g.*,m.username,m.money as money2')
                ->alias('g')
                ->join('tf_member m', 'g.user_id=m.id', 'LEFT')
                ->where($where)
                ->order($order)
                ->paginate('', false, page_param());
        $this->assign('dataList', $dataList);
        return $this->fetch();
    }

    //佣金
    public function profit() {
        $where = [];
        //导出
        if (input('get.search')) {
            $where['g.member_mobile|g.member_name|g.payment_sn|g.order_sn'] = ['like', '%' . trim(input('get.search')) . '%'];
        }
        if (isset($_GET['status']) && input('get.status') != -1) {  //状态
            $where['g.status'] = ['eq', input('get.status')];
            if (input('get.status') == 3) {
                $where['g.status'] = ['eq', '0'];
            }
        }
        if (input('get.start_date') && input('get.end_date')) { // 开始/结束同时存在
            $start_date = input('get.start_date') . ' 00:00:00';
            $end_date = input('get.end_date') . ' 23:59:59';
            $where['g.create_time'] = ['between time', [strtotime($start_date), strtotime($end_date)]];
        }
        $where['o.status'] = ['eq', 2];
        $order = 'g.id desc';
        if (input('get.down')) {
            $tableHeader = ['佣金订单编号', '原订单编号', '姓名', '手机号', '下级用户姓名', '下级认投金额', '直推佣金金额', '代付状态', '代付备注', '创建时间'];
            $dataList = $this->pModel
                    ->field('g.*')
                    ->alias('g')
                    ->join('tf_order o', 'g.order_sn=o.order_sn', 'LEFT')
                    ->where($where)
                    ->order($order)
                    ->select();
            $data = [];
            $orderModel = new Order();
            foreach ($dataList as $k => $v) {
                $data[$k]['payment_sn'] = $v['payment_sn'];
                $data[$k]['order_sn'] = $v['order_sn'];
                $data[$k]['member_name'] = $v['member_name'];
                $data[$k]['member_mobile'] = $v['member_mobile'];
                $data[$k]['subordinate_name'] = $v['subordinate_name'];
                $data[$k]['order_money'] = $v['order_money'];
                $data[$k]['money'] = $v['money'];
                if ($v['status'] == 0) {
                    $data[$k]['status'] = '待发放';
                } elseif ($v['status'] == 1) {
                    $data[$k]['status'] = '代付成功';
                } elseif ($v['status'] == 2) {
                    $data[$k]['status'] = '代付失败';
                }
                $data[$k]['remark'] = $v['remark'];
                $data[$k]['create_time'] = $v['create_time'];
            }
            ToPHPEXECL($tableHeader, $data, '佣金记录');
        }
        $dataList = $this->pModel
                ->field('g.*')
                ->alias('g')
                ->join('tf_order o', 'g.order_sn=o.order_sn', 'LEFT')
                ->where($where)
                ->order($order)
                ->paginate('', false, page_param());
        $this->assign('dataList', $dataList);
        $countTitle = $this->pModel
                        ->field('g.*')
                        ->alias('g')
                        ->join('tf_order o', 'g.order_sn=o.order_sn', 'LEFT')
                        ->where($where)
                        ->order($order)->select();
        $this->assign('countTitle', count($countTitle));
        return $this->fetch();
    }

    public function profitEdit() {
        $YunClass = new Yunst();
        $opModel = new OrderProfit();
        $post = input('post.');
        $data = $opModel->where(['id' => $post['id']])->find();
        if ($data) {
            if ($data['status'] == 1) {
                return ajaxReturn('该笔订单已经成功发放', url('profit'));
            }
            $subordinateBizUserId = $this->cModel->where(['id' => $data['member_id']])->value('bizUserId');

            if ($data['status'] == 2) {
                if (!empty($data['detail'])) {
                    $detail = unserialize($data['detail']);
                    $detail[$data['payment_sn']]['payment_sn'] = $data['payment_sn'];
                    $detail[$data['payment_sn']]['create_time'] = $data['update_time'];
                    $detail[$data['payment_sn']]['remark'] = $data['remark'];
                } else {
                    $detail[$data['payment_sn']]['payment_sn'] = $data['payment_sn'];
                    $detail[$data['payment_sn']]['create_time'] = $data['update_time'];
                    $detail[$data['payment_sn']]['remark'] = $data['remark'];
                }
                $payment_sn = 'HRY' . create_order();
                $detail = serialize($detail);
                $opModel->where(['id' => $data['id']])->update(['payment_sn' => $payment_sn, 'detail' => $detail]);
                $data = $opModel->where(['id' => $post['id']])->find();
            }
            $new_order = [
                'order_sn' => $data['payment_sn'],
                'money' => $data['money'],
            ];
            $updateTime = time();
            $new_message = $YunClass->PingTaiZhuanZhang($subordinateBizUserId, $new_order);
            if ($new_message['status'] != 'OK') {

                $opModel->where(['id' => $data['id']])->update(['status' => 2, 'update_time' => $updateTime, 'remark' => $new_message['message']]);
                return ajaxReturn($new_message['message']);
            } else {
                $opModel->where(['id' => $post['id']])->update(['status' => 1, 'remark' => '', 'update_time' => $updateTime]);
                $money = $this->cModel->where(['id' => $data['member_id']])->value('money');
                $new_money = $money + $data['money'];
                $this->cModel->where(['id' => $data['member_id']])->update(['money' => $new_money]);
                $memberData = $this->cModel->where(['id' => $data['subordinate_member_id']])->find();

                $str = substr_replace($memberData['mobile'], '****', 3, 4);
                $namestr = $memberData['username'];  //utf-8编码的字符串
                $name = mb_substr($namestr, 0, 1, 'utf-8') . '*';
                TobeNotice($data['member_id'], '佣金通知', '恭喜您！您手机号为' . $str . '的好友' . $name . '先生/女士认投项目' . $data['order_money'] . '元人民币，恭喜您获得好友奖励' . $data['money'] . '元人民币！');
                return ajaxReturn('发放成功', url('profit'));
            }
        }
    }

    //佣金发放记录

    public function profitdetail($id) {
        $opModel = new OrderProfit();
        $data = $opModel->where(['id' => $id])->find();
        $this->assign('data', unserialize($data['detail']));
        return $this->fetch();
    }

    public function create($user_id) {
        if (request()->isPost()) {
            Db::startTrans();
            try {
                $data = input('post.');
                $result = $this->rModel->validate('Recharge.add')->allowField(true)->save($data);
                $uid = $this->rModel->getLastInsID();
                // 提交事务
                if ($result && $uid) {
                    Db::commit();
                    if ($data['status'] == 2) {
                        $this->cModel->where('id', $data['user_id'])->setInc('money', $data['money']);
                        $Pmodel = new Putlog();
                        $log = [
                            'order' => 'OD' . create_order(),
                            'uid' => $data['user_id'],
                            'money' => $data['money'],
                            'type' => 2, //充值
                            'status' => 1,
                            'create_time' => time()
                        ];
                        $logid = $Pmodel->allowField(true)->save($log);
                    }
                    return ajaxReturn(lang('action_success'), url('recharge'));
                } else {
                    return ajaxReturn($this->rModel->getError());
                }
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return ajaxReturn($e->getMessage());
            }
        } else {
            $data = $this->cModel->where('id', 'eq', $user_id)->where('is_disable', 'eq', '1')->find();
            if (empty($data)) {
                $this->error('黑名单账户无法充值!');
            }
            $data['order'] = 'NO' . create_order();
            $this->assign('data', $data);
            return $this->fetch();
        }
    }

    public function edit($id) {
        if (request()->isPost()) {
            $data = input('post.');
            $result = $this->rModel->validate('Recharge.edit')->allowField(true)->save($data, $data['id']);
            if ($result) {
                return ajaxReturn(lang('action_success'), url('recharge'));
            } else {
                return ajaxReturn($this->rModel->getError());
            }
        } else {

            $data = $this->rModel->get($id);
            $data->member;
            $this->assign('data', $data);
            return $this->fetch();
        }
    }

    public function delete() {
        if (request()->isPost()) {
            $id = input('id');
            if (isset($id) && !empty($id)) {
                Db::startTrans();
                try {
                    $where = [ 'id' => ['eq', $id]];
                    $result = $this->rModel->where($where)->delete();   //删除数据
                    // 提交事务
                    if ($result) {
                        Db::commit();
                        return ajaxReturn(lang('action_success'), url('recharge'));
                    } else {
                        return ajaxReturn($this->cModel->getError());
                    }
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return ajaxReturn($e->getMessage());
                }
            }
        }
    }

    public function withdraw() {
        $where = [];
        if (!empty($_GET['status']) && input('get.status') != -1) {
            $where['g.status'] = ['eq', input('get.status')];
        }elseif ($_GET['status'] === '0'){
            $where['g.status'] = ['eq', 0];
        }
        if (input('get.start_date') && input('get.end_date')) { // 开始/结束同时存在
            $start_date = input('get.start_date') . ' 00:00:00';
            $end_date = input('get.end_date') . ' 23:59:59';
            $where['g.date'] = ['between time', [strtotime($start_date), strtotime($end_date)]];
        }
        if (input('get.search')) {
            $where['m.username|g.mobile'] = ['like', '%' . trim(input('get.search')) . '%'];
        }
        if (input('get._sort')) {
            $order = explode(',', input('get._sort'));
            $order = 'g.' . $order[0] . ' ' . $order[1];
        } else {
            $order = 'g.id desc';
        }
        //导出
        if (input('get.down')) {
            $tableHeader = ['会员', '会员电话','订单号', '提现姓名', '手机号', '开户行', '银行卡', '金额', '状态', '创建时间'];
            $dataList = $this->gModel
                    ->field('g.*,m.username,m.mobile as user_mobile,c.bank_number,c.bank_truename,c.bank_name')
                    ->alias('g')
                    ->join('tf_member m', 'g.user_id=m.id', 'LEFT')
                    ->join('tf_card c', 'g.card_id=c.id', 'LEFT')
                    ->where($where)
                    ->order($order)
                    ->select();
            $data = [];
            foreach ($dataList as $k => $v) {
                $data[$k]['username'] = $v['username'];
                $data[$k]['user_mobile'] = $v['user_mobile'];
                $data[$k]['order'] = $v['order'];
                $data[$k]['bank_truename'] = $v['bank_truename'];
                $data[$k]['mobile'] = $v['mobile'];
                $data[$k]['bank_name'] = $v['bank_name'];
                $data[$k]['bank_number'] = "\t" . $v['bank_number'];
                $data[$k]['money'] = $v['money'];
                if ($v['status'] == 2) {
                    $data[$k]['status'] = '已打款';
                } elseif ($v['status'] == 1) {
                    $data[$k]['status'] = '待打款';
                } elseif ($v['status'] == 3) {
                    $data[$k]['status'] = '已拒绝';
                } else {
                    $data[$k]['status'] = '待审核';
                }
                $data[$k]['date'] = $v['date'];
            }
            ToPHPEXECL($tableHeader, $data, '提现记录');
        }
        $dataList = $this->gModel
                ->field('g.*,m.username,m.mobile as user_mobile,c.bank_number,c.bank_truename,c.bank_name')
                ->alias('g')
                ->join('tf_member m', 'g.user_id=m.id', 'LEFT')
                ->join('tf_card c', 'g.card_id=c.id', 'LEFT')
                ->where($where)
                ->order($order)
                ->paginate('', false, page_param());
        $this->assign('dataList', $dataList);
        return $this->fetch();
    }

    public function look($id) {
        if (request()->isPost()) {
            $data = input('post.');
            if ($data['status'] == 3) {
                $this->Unagent($id);
            }
            if ($data['status'] == 1) {
                $res = $this->DaiFu($id);
            }
            $result = $this->gModel->allowField(true)->save($data, $data['id']);
            if ($result) {
                return ajaxReturn(lang('action_success'), url('withdraw'));
            } else {
                return ajaxReturn($this->gModel->getError());
            }
        } else {
            $data = $this->gModel
                    ->field('g.*,m.username,c.bank_number,c.bank_truename,c.bank_name,c.bank_address,c.bank_branch')
                    ->alias('g')
                    ->join('tf_member m', 'g.user_id=m.id', 'LEFT')
                    ->join('tf_card c', 'g.card_id=c.id', 'LEFT')
                    ->where('g.id=' . $id)
                    ->find();
            $this->assign('data', $data);
            return $this->fetch();
        }
    }

    public function remove($id) {
        if (request()->isPost()) {
            $id = input('id');
            if (isset($id) && !empty($id)) {
                Db::startTrans();
                try {
                    $where = [ 'id' => ['eq', $id], 'status' => ['eq', 3]];
                    $result = $this->gModel->where($where)->delete();   //删除数据
                    // 提交事务
                    if ($result) {
                        Db::commit();
                        return ajaxReturn(lang('action_success'), url('withdraw'));
                    } else {
                        return ajaxReturn($this->gModel->getError());
                    }
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return ajaxReturn($e->getMessage());
                }
            }
        }
    }

    public function support() {
        $orModel = new Order();
        $pModel = new Project();

        $where = [];
        if (isset($_GET['status']) && input('get.status') != -1) {
            $where['a.status'] = ['eq', input('get.status')];
        }
        if (isset($_GET['payment_status']) && input('get.payment_status') != -1) {
            $where['a.payment_status'] = ['eq', input('get.payment_status')];
        }
        if (input('get.project_id')) {
            $where['a.project_id'] = ['eq', input('get.project_id')];
        }
        if (input('get.start_date')) {
            $where['a.create_time'][] = ['gt', strtotime(input('get.start_date') . ' 00:00:00')];
        }
        if (input('get.end_date')) {
            $where['a.create_time'][] = ['lt', strtotime(input('get.end_date') . ' 23:59:59')];
        }
        if (input('get.search')) {
            $where['a.order_sn|a.money|b.username|b.mobile|c.project_name'] = ['like', '%' . input('get.search') . '%'];
        }
        if (input('get._sort')) {
            $order = explode(',', input('get._sort'));
            $order = $order[0] . ' ' . $order[1];
        } else {
            $order = 'id desc';
        }
        
        if (input('get.down')) {
            $tableHeader = ['订单号', '会员名称', '手机号', '支持金额', '所属项目', '状态', '代付状态','创建时间'];
            $dataList = $orModel->field('a.*,b.username,b.mobile,c.project_name')
                    ->alias('a')
                    ->join('tf_member b', 'a.uid=b.id', 'LEFT')
                    ->join('tf_project c', 'a.project_id=c.id', 'LEFT')
                    ->where($where)
                    ->order($order)
                    ->select();
            $data = [];
            
            foreach ($dataList as $k => $v) {
                $data[$k]['order_sn'] = $v['order_sn'];
                $data[$k]['username'] = $v['username'];
                $data[$k]['mobile'] = $v['mobile'] . ' ';
                $data[$k]['money'] = $v['money'];
                $data[$k]['project_name'] = $v['project_name'];
                if ($v['status'] == 2) {
                    $status = '已成功';
                } elseif ($v['status'] == 1) {
                    $status = '进行中';
                } elseif ($v['status'] == 0) {
                    $status = '未成功';
                } else {
                    $status = '其他状态';
                }
                if ($v['payment_status'] == 2) {
                    $payment_status = '已失败';
                } elseif ($v['payment_status'] == 1) {
                    $payment_status = '已成功';
                } elseif ($v['payment_status'] == 0) {
                    $payment_status = '待处理';
                } else {
                    $payment_status = '其他状态';
                }
                $data[$k]['status'] = $status;
                $data[$k]['payment_status'] = $payment_status;
                $data[$k]['create_time'] = $v['create_time'];
            }

            ToPHPEXECL($tableHeader, $data, '支持订单');
        }

        $dataList = $orModel->field('a.*,b.username,b.mobile,c.project_name')
                ->alias('a')
                ->join('tf_member b', 'a.uid=b.id', 'LEFT')
                ->join('tf_project c', 'a.project_id=c.id', 'LEFT')
                ->where($where)
                ->order($order)
                ->paginate('', false, page_param());
        $ProjectList = $pModel->field('id,project_name')->select();

        $this->assign('ProjectList', $ProjectList);
        $this->assign('dataList', $dataList);
        return $this->fetch();
    }

    //订单代付
    public function daifuz($id) {
        $orderClass = new Order();
        $YunClass = new Yunst();
        $memberClass = new Members();
        $orderPaymentClass = new OrderPayment();
        $orderData = $orderClass->where(['id' => $id])->find();


        $bizUserId = $memberClass->where(['id' => $orderData['uid']])->value('bizUserId');
        $bizOrderNo = 'HryDF' . $id . str_pad($bizUserId, 7, '0', STR_PAD_LEFT);
        $message = $YunClass->signalAgentPay2($bizOrderNo, $bizUserId, $orderData['order_sn'], $orderData['money']);
        if ($message['status'] == 'error') {
            $orderClass->where(['id' => $orderData['id']])->update(['payment_status' => 2, 'payment_remark' => $message['message']]);
            return ajaxReturn($message['message']);
        }
        if ($message['status'] == 'OK') {
            $payment_data = [];
            $member_data = $memberClass->where(['id' => $orderData['uid']])->find();
            $payment_data['project_id'] = $orderData['project_id'];
            $payment_data['order_sn'] = $orderData['order_sn'];
            $payment_data['money'] = $orderData['money'];
            $payment_data['status'] = 2;
            $payment_data['name'] = $member_data['username'];
            $payment_data['create_time'] = $orderData['create_time'];
            $payment_data['mobile'] = $member_data['mobile'];
            $payment_data['payment_time'] = time();
            $payment_data['uid'] = UID;
            $payment_data['remark'] = $message['remark'];
            $payment_data['number_id'] = $member_data['certificate'];
            $orderPaymentClass->insert($payment_data);
            $orderClass->where(['id' => $orderData['id']])->update(['payment_status' => 1]);
            return ajaxReturn('代付成功');
        }
    }

    private function Unagent($id) {
        $Info = $this->gModel->where(['id' => $id])->find();
        $res = $this->cModel->where(['id' => $Info['user_id']])->setInc('money', $Info['money']);
        $logModel = new Putlog();
        $log = [
            'uid' => $Info['user_id'],
            'money' => $Info['money'],
            'type' => 3, //退还
            'order' => 'OD' . create_order(),
            'status' => 1,
            'crate_time' => time()
        ];
        $logModel->allowField(true)->save($log);
        TobeNotice($Info['user_id'], '提现通知', '您的提现申请被拒绝,余额已返回账户。');
    }

    private function DaiFu($id) {
        $YunClass = new Yunst();

        $Info = $this->gModel
                        ->alias('a')
                        ->field('a.*,b.bank_number as bankCardNo')
                        ->join('tf_card b', 'a.card_id=b.id', 'LEFT')
                        ->where(['a.id' => $id])->find();
        $bizUserId = $this->cModel->where(['id' => $Info['user_id']])->value('bizUserId');
        $message = $YunClass->TiMoney($bizUserId, $Info);
        if ($message['status'] == 'error') {
            return ajaxReturn($message['message']);
        }
//        if ($message['status'] == 'OK') {
//            TobeNotice($Info['user_id'], '提现通知', '您的提现申请已成功,请随时留意银行信息。');
//        }
    }
    
    /*
     * 会员对账
     * 
     * @param mixed $user 用户信息
     * @param mixed $recharge 充值金额
     * @param mixed $recruit 认投金额
     * @param mixed $withdraw 提现金额
     * @param mixed $promotion 推广金额
     * @param mixed $fee 手续费
     * @author cpy(1442435897@qq.com)
     * @return array
     */
    public function memberList(Order $orderModel,SubAccount $subModel,Project $projectModel) {
        $param = request()->param();
        if ($param) {
            if (empty($param['phone']) && empty($param['down']))
                $this->error('手机号不能为空！');
            if($param['down']){
                $where['id'] = ['eq', $param['id']];
            }else{
                $where['mobile'] = ['eq', $param['phone']];
            }
            $user = $this->cModel->findInfo($where, 'id,username,mobile');
            $rwhere['user_id'] = ['eq', $user['id']];
            $rwhere['status'] = ['eq', 2];
            $rwhere['date'] = ['> time', '2018-11-14'];
            $recharge = $this->rModel->selectInfo($rwhere, 'sum(money),sum(fee)');
            $rewhere['uid'] = ['eq', $user['id']];
            $rewhere['status'] = ['in',[2,3]];
            $rewhere['type'] = ['eq', 1];
            $rewhere['create_times'] = ['> time', '2018-11-14'];
            $recruit = $orderModel->selectInfo($rewhere, 'sum(money)');
            unset($rewhere['create_times']);
            $rewhere['date'] = ['> time', '2018-11-14'];
            $withdraw = $this->gModel->selectInfo($rwhere, 'sum(money),sum(fee)');
            $pwhere['member_id'] = ['eq', $user['id']];
            $pwhere['status'] = ['eq', 1];
            $pwhere['create_time'] = ['> time', '2018-11-14'];
            $promotion = $this->pModel->selectInfo($pwhere, 'sum(money)');
            $fee = $recharge[0]['sum(fee)'] + $withdraw[0]['sum(fee)'];
            $swhere['user_id'] = ['eq',$user['id']];
            $subAccount = $subModel->selectInfo($swhere, 'sum(money)');
            
            $prowhere['status'] = ['>=',3];
            $project = $projectModel->selectInfo($prowhere,'id,project_name');
            
            $info['recharge'] = empty($recharge[0]['sum(money)']) ? 0 : $recharge[0]['sum(money)'];
            $info['recruit'] = empty($recruit[0]['sum(money)']) ? 0 : $recruit[0]['sum(money)'];
            $info['withdraw'] = empty($withdraw[0]['sum(money)']) ? 0 : $withdraw[0]['sum(money)'];
            $info['promotion'] = empty($promotion[0]['sum(money)']) ? 0 : $promotion[0]['sum(money)'];
            $info['fee'] = empty($fee) ? 0 : $fee;
            $info['subaccount'] = empty($subAccount[0]['sum(money)']) ? 0 : $subAccount[0]['sum(money)'];
            $info['balance'] = $info['recharge'] + $info['promotion'] - $info['recruit'] - $info['withdraw'] + $info['subaccount'];
            $info['balance'] = number_format($info['balance'],2);
            if ($param['name'] != $user['username']) {
                $info['same'] = empty($param['name']) ? 'YES' : 'NO';  
            } else {
                $info['same'] = 'YES';
            }
            if(empty($user)){
                $info['same'] = 'NULL';
            }
            
            if ($param['down']) {
                $tableHeader = ['对账类型', '总金额（元）'];
                $data[0]['name'] = '充值金额';
                $data[0]['money'] = $info['recharge'];
                $data[1]['name'] = '认投金额';
                $data[1]['money'] = $info['recruit'];
                $data[2]['name'] = '提现金额';
                $data[2]['money'] = $info['withdraw'];
                $data[3]['name'] = '推广金额';
                $data[3]['money'] = $info['promotion'];
                $data[4]['name'] = '手续费';
                $data[4]['money'] = $info['fee'];
                $data[5]['name'] = '分账金额';
                $data[5]['money'] = $info['subaccount'];
                $data[6]['name'] = '实时余额';
                $data[6]['money'] = $info['balance'];
                ToPHPEXECL($tableHeader, $data, '会员账户情况');
            }

            $this->assign('user', $user);
            $this->assign('dataList', $info);
            $this->assign('phone', $param['phone']);
            $this->assign('name', $param['name']);
            $this->assign('project', $project);
        }
        return $this->fetch();
    }

    /*
     * 会员对账-充值明细
     * 
     * @param mixed $startTime 开始时间
     * @param mixed endTime 结束时间
     * @author cpy(1442435897@qq.com)
     * @return array
     */
    public function memberDetails() {
        $param = request()->param();
        if(!empty($param['status']))
            $where['type'] = ['eq',$param['status']];
        if($param['_sort']){
            $sortArr = explode(',', $param['_sort']);
            $sort = 'a.'.$sortArr[0].' '.$sortArr[1];
        }else{
            $sort = 'a.id desc';
        }
        $startTime = empty($param['start_date'])?'2018-11-14':$param['start_date'];
        $endTime = empty($param['end_date'])?date('Y-m-d H:i:s'):$param['end_date'];
        $where['a.status'] = ['eq',2];
        $where['b.id'] = ['eq',$param['id']];
        $res = $this->rModel->memberRechargeDetails($where,$startTime,$endTime,$sort,'a.id,b.id as user_id,username,a.mobile,a.money,orderNo,a.date,a.bankcard,a.type');
        
        if($param['down']){
            $tableHeader = ['订单id','姓名','手机号码','金额','订单号','创建时间','银行卡号','类型'];
            $data = [];
            $row = $res ->toArray();
            foreach($row['data'] as $k=>$v){
                $data[$k]['id'] =  $v['id'];
                $data[$k]['name'] = $v['username'];
                $data[$k]['mobile'] =  $v['mobile'];
                $data[$k]['money'] =  $v['money'];
                $data[$k]['order'] =  $v['order'];
                $data[$k]['date'] =  $v['date'];
                $data[$k]['bankcard'] =  $v['bankcard'];
                if($v['type'] == 1){
                    $data[$k]['type'] =  '网银';
                }else{
                    $data[$k]['type'] =  '快捷';
                }
            }
            ToPHPEXECL($tableHeader,$data,'会员充值明细列表');
        }
        
        $this->assign('dataList', $res);
        $this->assign('user', $param['id']);
        $this->assign('param', $param);
        return $this->fetch();
    }
    
    /*
     * 会员对账-认投明细
     * @param mixed $startTime 开始时间
     * @param mixed $endTime 结束时间
     * @author cpy(1442435897@qq.com)
     * @return array
     */
    public function moneyRecruit(Order $orderModel) {
        $param = request()->param();
        if(!empty($param['project_id']))
            $where['c.id'] = ['eq',$param['project_id']];
        if($param['_sort']){
            $sortArr = explode(',', $param['_sort']);
            $sort = 'a.'.$sortArr[0].' '.$sortArr[1];
        }else{
            $sort = 'a.id desc';
        }
        $startTime = empty($param['start_date'])?'2018-11-14':$param['start_date'];
        $endTime = empty($param['end_date'])?date('Y-m-d H:i:s'):$param['end_date'];
        $where['a.status'] = ['in',[2,3]];
        $where['a.type'] = ['eq',1];
        $where['a.uid'] = ['eq',$param['id']];
        $res = $orderModel->memberRecruitDetails($where,$startTime,$endTime,$sort,'a.id,b.id as user_id,username,b.mobile,a.money,order_sn,a.create_times,c.id as project_id,c.project_name');
        $pwhere['uid'] = ['eq',$param['id']];
        $project = $orderModel->memberRecruitProject($pwhere,'c.id,c.project_name');
        $key = 'id';
        $project = assoc_unique($project, $key);
        
        if($param['down']){
            $tableHeader = ['订单id','姓名','手机号码','认投金额','所属项目','订单号','创建时间'];
            $data = [];
            $row = $res ->toArray();
            foreach($row['data'] as $k=>$v){
                $data[$k]['id'] =  $v['id'];
                $data[$k]['name'] = $v['username'];
                $data[$k]['mobile'] =  $v['mobile'];
                $data[$k]['money'] =  $v['money'];
                $data[$k]['project_name'] =  $v['project_name'];
                $data[$k]['order'] =  $v['order_sn'];
                $data[$k]['date'] =  $v['create_times'];
            }
            ToPHPEXECL($tableHeader,$data,'认投账户列表');
        }
        
        $this->assign('dataList', $res);
        $this->assign('project', $project);
        $this->assign('user', $param);
        return $this->fetch();
    }
    
    /*
     * 会员对账-提现明细
     * @param mixed $startTime 开始时间
     * @param mixed $endTime 结束时间
     * @author cpy(1442435897@qq.com)
     * @return array
     */
    public function moneyReflect() {
        $param = request()->param();
        $where['b.id'] = ['eq',$param['id']];
        if($param['status']) {
            if ($param['status'] == 4)
                $status = 0;
            $where['a.status'] = ['eq', $status];
        }
        if($param['_sort']){
            $sortArr = explode(',', $param['_sort']);
            if($sortArr[0] == 'date'){
                $sort = 'UNIX_TIMESTAMP(a.'.$sortArr[0].') '.$sortArr[1];
            }else{
                $sort = 'a.'.$sortArr[0].' '.$sortArr[1];
            }
        }else{
            $sort = 'a.id desc';
        }
        $startTime = empty($param['start_date'])?'2018-11-14':$param['start_date'];
        $endTime = empty($param['end_date'])?date('Y-m-d H:i:s'):$param['end_date'];
        $res = $this->gModel->memberGetcashDetails($where,$startTime,$endTime,$sort,'a.id,b.id as user_id,username,a.mobile,c.bank_name,c.bank_number,a.order,a.date,a.money,a.fee,a.status,(a.money - a.fee) as num');
        
        if($param['down']){
            $tableHeader = ['订单id','姓名','手机号码','开户行','银行卡号','订单号','创建时间','提现金额','手续费','状态','到账金额'];
            $data = [];
            $row = $res ->toArray();
            foreach($row['data'] as $k=>$v){
                $data[$k]['id'] =  $v['id'];
                $data[$k]['name'] = $v['username'];
                $data[$k]['mobile'] =  $v['mobile'];
                $data[$k]['bank_name'] =  $v['bank_name'];
                $data[$k]['bank_number'] =  $v['bank_number'];
                $data[$k]['order'] =  $v['order'];
                $data[$k]['date'] =  $v['date'];
                $data[$k]['money'] =  $v['money'];
                $data[$k]['fee'] =  $v['fee'];
                if ($v['status'] === 0) {
                    $data[$k]['status'] = '待审核';
                } elseif ($v['status'] == 1) {
                    $data[$k]['status'] = '进行中';
                } elseif ($v['status'] == 2) {
                    $data[$k]['status'] = '成功';
                } else {
                    $data[$k]['status'] = '拒绝';
                }
                $data[$k]['num'] =  $v['num'];
            }
            ToPHPEXECL($tableHeader,$data,'会员提现明细列表');
        }
        
        $this->assign('dataList', $res);
        $this->assign('user', $param);
        return $this->fetch();
    }
    
    /*
     * 会员对账-推广明细
     * @param mixed $startTime 开始时间
     * @param mixed $endTime 结束时间
     * @author cpy(1442435897@qq.com)
     * @return array
     */
    public function moneyPromotion() {
        $param = request()->param();
        $where['member_id'] = ['eq',$param['id']];
        if($param['name']) 
            $where['subordinate_name'] = ['like','%'.$param['name'].'%'];
        if($param['_sort']){
            $sortArr = explode(',', $param['_sort']);
            $sort = $sortArr[0].' '.$sortArr[1];
        }else{
            $sort = 'create_time desc';
        }
        $startTime = empty($param['start_date'])?'2018-11-14':$param['start_date'];
        $endTime = empty($param['end_date'])?date('Y-m-d H:i:s'):$param['end_date'];
        $res = $this->pModel->memberPromotionDetails($where,$startTime,$endTime,$sort);
        
        if($param['down']){
            $tableHeader = ['姓名','手机号','下级用户姓名','下级认投金额','推广金额','时间'];
            $data = [];
            $row = $res ->toArray();
            foreach($row['data'] as $k=>$v){
                $data[$k]['member_name'] =  $v['member_name'];
                $data[$k]['member_mobile'] = $v['member_mobile'];
                $data[$k]['subordinate_name'] =  $v['subordinate_name'];
                $data[$k]['order_money'] =  $v['order_money'];
                $data[$k]['money'] =  $v['money'];
                $data[$k]['create_time'] =  $v['create_time'];
            }
            ToPHPEXECL($tableHeader,$data,'会员提现明细列表');
        }
        
        $this->assign('dataList', $res);
        $this->assign('user', $param);
        return $this->fetch();
    }
    
    /*
     * 会员对账-手续费明细
     * @param mixed $startTime 开始时间
     * @param mixed $endTime 结束时间
     * @author cpy(1442435897@qq.com)
     * @return array
     */
    public function moneyFee() {
        $param = request()->param();
        $where['a.id'] = ['eq',$param['id']];
        $startTime = empty($param['start_date'])?'2018-11-14':$param['start_date'];
        $endTime = empty($param['end_date'])?date('Y-m-d H:i:s'):$param['end_date'];
        if($param['status'] == 1) {
            if($param['_sort']){
                $sortArr = explode(',', $param['_sort']);
                $sort = 'b.'.$sortArr[0].' '.$sortArr[1];
            }else{
                $sort = 'b.id desc';
            }
            $where['b.status'] = ['eq',2];
            $res = $this->cModel->memberRechargeFeeDetails($where,$startTime,$endTime,$sort,'a.username,b.id as recharge_id,b.order as ordernum,b.date as date,b.fee as money,1 as type');
        }  elseif ($param['status'] == 2) {
            if($param['_sort']){
                $sortArr = explode(',', $param['_sort']);
                $sort = 'c.'.$sortArr[0].' '.$sortArr[1];
            }else{
                $sort = 'c.id desc';
            }
            $where['c.status'] = ['eq',2];
            $res = $this->cModel->memberGetcashFeeDetails($where,$startTime,$endTime,$sort,'a.username,c.id as getcash_id,c.order as ordernum,c.date as date,c.fee as money,2 as type');
        }else{
            if($param['_sort']){
                $sortArr = explode(',', $param['_sort']);
                $sort = $sortArr[0].' '.$sortArr[1];
            }else{
                $sort = 'date desc';
            }
            $res = $this->cModel->memberFeeDetails($where,$startTime,$endTime,$sort,'a.username,b.id as order_id,b.`order` as ordernum,b.date as date,b.fee as money,'
                    . 'b.status as status,1 as type','a.username,c.id as order_id,c.`order` as ordernum,c.date as date,c.fee as money,c.status as status,2 as type');
        }
        
        if($param['down']){
            $tableHeader = ['姓名','订单号','创建时间','金额','类型'];
            $data = [];
            $row = $res->toArray();
            foreach ($row['data'] as $k => $v) {
                $data[$k]['username'] = $v['username'];
                $data[$k]['order'] = empty($v['getcash_id']) ? $v['recharge_order'] : $v['getcash_order'];
                $data[$k]['date'] = empty($v['getcash_id']) ? $v['redate'] : $v['gedate'];
                $data[$k]['money'] = empty($v['getcash_id']) ? $v['remoney'] : $v['gemoney'];
                $data[$k]['type'] = empty($v['getcash_id']) ? '充值' : '提现';
            }
            ToPHPEXECL($tableHeader,$data,'会员手续费明细列表');
        }
        
        $this->assign('dataList', $res);
        $this->assign('user', $param);
        return $this->fetch();
    }
    
    /*
     * 会员对账-分账明细
     * @param mixed $startTime 开始时间
     * @param mixed $endTime 结束时间
     * @author cpy(1442435897@qq.com)
     * @return array
     */
    public function moneySubAccount(SubAccount $subModel) {
        $param = request()->param();
        if(!empty($param['project_id']))
            $where['a.project_id'] = ['eq',$param['project_id']];
        if($param['_sort']){
            $sortArr = explode(',', $param['_sort']);
            $sort = 'a.'.$sortArr[0].' '.$sortArr[1];
        }else{
            $sort = 'a.create_time desc';
        }
        $startTime = empty($param['start_date'])?'2018-11-14':$param['start_date'];
        $endTime = empty($param['end_date'])?date('Y-m-d H:i:s'):$param['end_date'];
        $where['a.user_id'] = ['eq',$param['id']];
        $res = $subModel->memberRecruitDetails($where,$startTime,$endTime,$sort,'a.*,b.username,b.mobile,c.project_name');
        $pwhere['a.user_id'] = ['eq',$param['id']];
        $project = $subModel->memberRecruitProject($pwhere,'c.id,c.project_name');
        $key = 'id';
        $project = assoc_unique($project, $key);
        
        if($param['down']){
            $tableHeader = ['id','姓名','手机号码','分账金额','所属项目','创建时间'];
            $data = [];
            $row = $res ->toArray();
            foreach($row['data'] as $k=>$v){
                $data[$k]['id'] =  $v['id'];
                $data[$k]['name'] = $v['username'];
                $data[$k]['mobile'] =  $v['mobile'];
                $data[$k]['money'] =  $v['money'];
                $data[$k]['project_name'] =  $v['project_name'];
                $data[$k]['date'] =  $v['create_time'];
            }
            ToPHPEXECL($tableHeader,$data,'认投账户列表');
        }
        
        $this->assign('dataList', $res);
        $this->assign('project', $project);
        $this->assign('user', $param);
        return $this->fetch();
    }
    
    /**
     * 分账结算
     * @author cpy(1442435897@qq.com)
     * @return array
     */
    public function memberSettlement() {
        $param = request()->param();
        if ($param) {
            $user_model = new user;
            $subaccount = new SubAccount;
            $user_id = UID;
            $money = floatval(trim($param['money']));
            $password = md5(trim($param['password']));
            $user_info = $user_model->getUserInfo($user_id);
            if (empty($user_info) || empty($user_info['finance_password'])) {
                $res['info'] = '抱歉,您没有权限!';
                return ajaxReturn($res);
            }
            if ($user_info['finance_password'] == $password) {
                $data['user_id'] = $param['user_id'];
                $data['project_id'] = $param['project'];
                $data['money'] = $money;
                $data['admin_id'] = $user_id;
                $data['create_time'] = time();
                $data['ip'] = $_SERVER['REMOTE_ADDR'];
                $update = $subaccount->insert($data);
            }else{
                $res['info'] = '密码错误!';
                return ajaxReturn($res);
            }
            if ($update) {
                $res['info'] = '结算成功!';
                $res['status'] = 1;
                return ajaxReturn($res);
            } else {
                $res['info'] = '结算失败!';
                return ajaxReturn($res);
            }
        } else {
            return ajaxReturn('参数错误');
        }
    }

    /**
     *公司对账首页
     * @author hey_heyang(635870453@qq.com)
     */
    public function companyList() {
        $order_model = new order;
        if(input('get.end_time')){
            $end_time=strtotime(input('get.end_time'))+86400-1; //获取指定时间当天的23:59:59
        }else{
            $end_time=date('Y-m-d 23:59:59', time()); //今天的23:59:59
            $end_time = strtotime($end_time);
            $_GET['end_time']=date('Y-m-d',$end_time);
        }
        $const_start_time =strtotime('2018-11-14 0:00:00') ;

        //认投账户集
        $pass_by_total_money = $order_model->getAddAnotherMoney($const_start_time,$end_time); //未在系统记录的代付总金额
        $pay_for_member_total = $order_model->getPayForMember($const_start_time,$end_time);
        $order_member_total = $order_model->getOrderMember($const_start_time,$end_time);
        $pay_for_total = floatval($order_member_total)-($pay_for_member_total)-floatval($pass_by_total_money);

        //手续费账户集
        $pt_get_total = $order_model->getPtfeeTotal($const_start_time,$end_time);//平台提取的手续费
        $tx_fee_total = $order_model->getTxfeeTotal($const_start_time,$end_time); // 提现手续费
        $cz_fee_total = $order_model->getCzfeeTotal($const_start_time,$end_time);//充值手续费
        $total_fee = floatval($tx_fee_total)+floatval($cz_fee_total)-floatval($pt_get_total);

        //推广账户集
        $pt_charge_total = $order_model->getPtChargeTotal($const_start_time,$end_time);//平台充值的推广金
        $member_charge_total = $order_model->getMemberChargeTotal($const_start_time,$end_time);//直推佣金总额
        $jiesuan_money = $order_model->getJsMoney($const_start_time,$end_time);//推广账户集结算金额
        $tg_total = floatval($pt_charge_total)-floatval($member_charge_total)-floatval($jiesuan_money);

        //备用金
        $bak_money = floatval(200);

        //用户总余额
        $member_money_total =$order_model->getMemberMoneyTotal($end_time); //需按时间来筛选
        $not_df_money = $order_model->getNotDfMoney($const_start_time,$end_time); //未代付的金额
        $member_money_total =floatval($member_money_total)+floatval($not_df_money);

        $total_all=$pay_for_total + $total_fee + $tg_total + $bak_money + $member_money_total;

        $datas=array();
        $datas['pay_for_total'] =$pay_for_total;
        $datas['total_fee'] =$total_fee;
        $datas['tg_total'] =$tg_total;
        $datas['bak_money'] =$bak_money;
        $datas['member_money_total'] =$member_money_total;
        $datas['total_all'] =$total_all;
        $this->assign('datas',$datas);
        return $this->fetch();
    }

    /**
     *认投账户详情
     * @author hey_heyang(635870453@qq.com)
     */
    public function detailForVote(){
        $op_model = new orderPayment;
        $project_model = new project;
        if(input('_sort')){
            $sort_list = explode(',', input('_sort'));
            $sort_type = $sort_list[1];
        }else{
            $sort_type = 'desc';
        }
        $pagesize = input('pagesize')?input('pagesize'):20;
        if(intval(input('project_id'))>0){
            $condition1['p.id']=input('project_id');
            $condition2['p.id']=input('project_id');
        }
        if(input('start_date') && input('end_date')){
            $time1 = strtotime(input('start_date'));
            $time2 = strtotime(input('end_date').'+ 1 day');
            $condition1['o.create_time'] = array('between',$time1.','.$time2);
            $condition2['op.payment_time']= array('between',$time1.','.$time2);
        }elseif(input('star_date')){
            $condition1['o.create_time'] = array('eqt',strtotime(input('start_date')));
            $condition2['op.payment_time']=array('eqt',strtotime(input('start_date')));
        }elseif(input('end_date')){
            $condition1['o.create_time'] = array('elt',strtotime(input('end_date').'+ 1 day')-1);
            $condition2['op.payment_time']=array('elt',strtotime(input('end_date').'+ 1 day')-1);
        }

        $condition1['o.type'] = 1;  //认投
        $condition1['o.status'] = array('in','2,3');  //认投成功
        $condition2['op.status'] = 2; //代付成功
        $field1='FROM_UNIXTIME(o.create_time) as time,p.project_name,m.username,m.mobile,o.money,1 as type';
        $field2='FROM_UNIXTIME(op.payment_time) as time,p.project_name,m.username,m.mobile,op.money,2 as type';
        $dataList = $op_model->getTotalListData($condition1,$condition2,$field1,$field2,$pagesize,$sort_type);
        if(input('down')){
            $tableHeader = ['时间','所属项目','姓名','手机号码','金额'];
            $field1='FROM_UNIXTIME(o.create_time) as time,p.project_name,m.username,m.mobile,CONCAT("+",o.money)';
            $field2='FROM_UNIXTIME(op.payment_time) as time,p.project_name,m.username,m.mobile,CONCAT("-",op.money)';
            $exceldatalist =$op_model->getExcelTotalListData($condition1,$condition2,$field1,$field2,$pagesize,$sort_type);

            ToPHPEXECL($tableHeader,$exceldatalist,'认投账户列表');   //下载数据列表
        }


        $project_list=$project_model->select();
        $this->assign('project_list',$project_list);
        $this->assign('dataList',$dataList);
        return  $this->fetch();



    }



    /**
     * 手续费账户提取
     * @author hey_heyang(635870453@qq.com)
     */
    public function modifyMoney(){
        $const_start_time =strtotime('2018-11-14 0:00:00') ;
        if (request()->isPost()){
            $user_model = new user;
            $atmoney = new AddAnotherMoneyInfo;
            $user_id=UID;
            $money = floatval(trim($_POST['money']));
            $password = md5(trim($_POST['password']));
            $user_info =$user_model->getUserInfo($user_id);
            if(empty($user_info) || empty($user_info['finance_password'])){
                return ajaxReturn('抱歉,您没有权限!');
            }
            if($user_info['finance_password']==$password){
                $data['user_id'] = $user_id;
                $data['type'] = 2; //手续费提取
                $data['money'] = $money;
                $data['status'] = 1;
                $data['payment_time'] = time();
                $data['ip'] = $_SERVER['REMOTE_ADDR'];
                $update = $atmoney->insert($data);
            }
            if($update){
                return ajaxReturn('提取成功','',1);
            }else{
                return ajaxReturn('提取失败');
            }



        }else{
            return ajaxReturn('参数错误');
        }

    }



    /**
     * 测试请求查询平台账户集余额
     */

    public function queryAccountInfo(){
        if(request()->isPost()){
            $user_model = new user;
            $user_id=UID;
            $password = md5(trim($_POST['password']));
            $user_info =$user_model->getUserInfo($user_id);
            if(empty($user_info) || empty($user_info['finance_password']) || $user_info['finance_password']!=$password){
                ajaxReturn('抱歉,您没有权限!');
            }
            $YunClass = new Yunst();
            $account = '100004';
            $res = $YunClass->queryAccount($account);
            $data = json_decode($res['signedValue'],true);
            $data['allAmount']=number_format($data['allAmount']/100,2);
            $data['freezeAmount']=number_format($data['freezenAmount']/100,2);
            ajaxReturn('操作成功','',1,$data);
        }
    }


    /**
     * 推广账户充值
     * @author hey_heyang(635870453@qq.com)
     */
    public function modifyTgMoney(){
        $const_start_time =strtotime('2018-11-14 0:00:00') ;
        if (request()->isPost()){
            $user_model = new user;
            $atmoney = new AddAnotherMoneyInfo;
            $user_id=UID;
            $money = floatval(trim($_POST['money']));
            $password = md5(trim($_POST['password']));
            $user_info =$user_model->getUserInfo($user_id);
            if(empty($user_info) || empty($user_info['finance_password'])){
                return ajaxReturn('抱歉,您没有权限!');
            }
            if($user_info['finance_password']==$password){
                $data['user_id'] = $user_id;
                $data['type'] = 3; //平台充值
                $data['money'] = $money;
                $data['status'] = 1;
                $data['payment_time'] = time();
                $data['ip'] = $_SERVER['REMOTE_ADDR'];
                $update = $atmoney->insert($data);
            }
            if($update){
                return ajaxReturn('充值成功','',1);
            }else{
                return ajaxReturn('充值失败');
            }



        }else{
            return ajaxReturn('参数错误');
        }

    }


    /**
     * 推广账户结算
     * @author hey_heyang(635870453@qq.com)
     */
    public function modifyJsMoney(){
        $const_start_time =strtotime('2018-11-14 0:00:00') ;
        if (request()->isPost()){
            $user_model = new user;
            $atmoney = new AddAnotherMoneyInfo;
            $user_id=UID;
            $money = floatval(trim($_POST['money']));
            $password = md5(trim($_POST['password']));
            $user_info =$user_model->getUserInfo($user_id);
            if(empty($user_info) || empty($user_info['finance_password'])){
                return ajaxReturn('抱歉,您没有权限!');
            }
            if($user_info['finance_password']==$password){
                $data['user_id'] = $user_id;
                $data['type'] = 4; //推广账户集结算金额
                $data['money'] = $money;
                $data['status'] = 1;
                $data['payment_time'] = time();
                $data['ip'] = $_SERVER['REMOTE_ADDR'];
                $update = $atmoney->insert($data);
            }
            if($update){
                return ajaxReturn('结算成功','',1);
            }else{
                return ajaxReturn('结算失败');
            }



        }else{
            return ajaxReturn('参数错误');
        }

    }






    /**
     * 手续费账户集详情
     * @author hey_heyang(635870453@qq.com)
     */
    public function detailForCommissionCharge(){
        $gc_model = new Getcash;
        $rc_model = new Recharge;
        $another_model = new AddAnotherMoneyInfo;  //手续费提取为type为2
        if(input('_sort')){
            $sort_list = explode(',', input('_sort'));
            $sort_type = $sort_list[1];
        }else{
            $sort_type = 'desc';
        }
        $pagesize = input('pagesize')?input('pagesize'):20;
        if(intval(input('status'))==0){  //获取全部
            $dataList = $gc_model->getTotalFeeList(input('start_date'),input('end_date'),$pagesize,$sort_type);
        }elseif(intval(input('status'))==1){ //充值手续费详情
            $dataList = $rc_model->getRcList(input('start_date'),input('end_date'),$pagesize,$sort_type);
        }elseif(intval(input('status'))==2){ //提现手续费详情
            $dataList = $gc_model->getGcList(input('start_date'),input('end_date'),$pagesize,$sort_type);
        }elseif(intval(input('status'))==3){ //提现到银行卡
            $dataList = $another_model->getAnotherList(input('start_date'),input('end_date'),$pagesize,$sort_type);
        }


        if(input('down')){
            $tableHeader = ['时间','姓名','手机号','金额','类型'];
            if(intval(input('status'))==0){  //获取全部
                $data = $gc_model->getTotalFeeList(input('start_date'),input('end_date'),$pagesize,$sort_type,true);
            }elseif(intval(input('status'))==1){ //充值手续费详情
                $data = $rc_model->getRcList(input('start_date'),input('end_date'),$pagesize,$sort_type,true);
            }elseif(intval(input('status'))==2){ //提现手续费详情
                $data = $gc_model->getGcList(input('start_date'),input('end_date'),$pagesize,$sort_type,true);
            }elseif(intval(input('status'))==3){ //提现到银行卡
                $data = $another_model->getAnotherList(input('start_date'),input('end_date'),$pagesize,$sort_type,true);
            }

            ToPHPEXECL($tableHeader,$data,'手续费账户详情列表');   //下载数据列表
        }

        $this->assign('dataList',$dataList);
        return  $this->fetch();

    }


    /**
     * 推广账户集详情
     * @author hey_heyang(635870453@qq.com)
     */
    public function detailForExtend(){
        $or_model = new OrderProfit;
        $another_model = new AddAnotherMoneyInfo;  //推广费充值type为3
        if(input('_sort')){
            $sort_list = explode(',', input('_sort'));
            $sort_type = $sort_list[1];
        }else{
            $sort_type = 'desc';
        }
        $pagesize = input('pagesize') ?input('pagesize'):20;
        if(intval(input('status'))==0){  //获取全部
            $dataList = $or_model->getTgTotalList(input('start_date'),input('end_date'),$pagesize,$sort_type);
        }elseif(intval(input('status'))==1){ //平台充值详情
            $dataList = $another_model->getAnotherChargeList(input('start_date'),input('end_date'),$pagesize,$sort_type);
        }elseif(intval(input('status'))==2){ //佣金发放详情
            $dataList = $or_model->getMemberYjList(input('start_date'),input('end_date'),$pagesize,$sort_type);
        }elseif(intval(input('status'))==3){ //推广账户集结算详情
            $dataList = $another_model->getAnotherJsList(input('start_date'),input('end_date'),$pagesize,$sort_type);
        }


        if(input('down')){
            $tableHeader = ['时间','到账姓名','到账账号','金额','类型'];
            if(intval(input('status'))==0){  //获取全部
                $data = $or_model->getTgTotalList(input('start_date'),input('end_date'),$pagesize,$sort_type,true);
            }elseif(intval(input('status'))==1){ //平台充值详情
                $data = $another_model->getAnotherChargeList(input('start_date'),input('end_date'),$pagesize,$sort_type,true);
            }elseif(intval(input('status'))==2){ //佣金发放详情
                $data = $or_model->getMemberYjList(input('start_date'),input('end_date'),$pagesize,$sort_type,true);
            }elseif(intval(input('status'))==3){ //推广账户集结算详情
                $data = $another_model->getAnotherJsList(input('start_date'),input('end_date'),$pagesize,$sort_type,true);
            }

            ToPHPEXECL($tableHeader,$data,'推广账户详情列表');   //下载数据列表
        }

        $this->assign('dataList',$dataList);
        return  $this->fetch();



    }

    /**
     * 项目兑付
     * @author kangyi(997032813@qq.com)
     */
    public function cashPaymentIndex() {
        $orModel = new Order();
        $pModel = new Project();

        $where = [];
        if (isset($_GET['cash_payment_status']) && input('get.cash_payment_status') != -1) {
            $where['a.cash_payment_status'] = ['eq', input('get.cash_payment_status')];
        }
        if (input('get.search')) {
            $where['a.order_sn|a.money|b.username|b.mobile|c.project_name'] = ['like', '%' . input('get.search') . '%'];
        }
        $order = 'money desc';
        $where['a.project_id'] = 16;
        $where['a.status'] = 2;
        if (input('get.down')) {
            $tableHeader = ['订单ID','会员名称', '手机号', '认投金额', '所属项目', '订单号','创建时间', '认投状态', '兑付状态','兑付备注','兑付金额'];
            $dataList = $orModel->field('a.*,b.username,b.mobile,c.project_name')
                ->alias('a')
                ->join('tf_member b', 'a.uid=b.id', 'LEFT')
                ->join('tf_project c', 'a.project_id=c.id', 'LEFT')
                ->where($where)
                ->order($order)
                ->select();
            $data = [];

            foreach ($dataList as $k => $v) {
                $data[$k]['id'] = $v['id'];
                $data[$k]['username'] = $v['username'];
                $data[$k]['mobile'] = $v['mobile'] . ' ';
                $data[$k]['money'] = $v['money'];
                $data[$k]['project_name'] = $v['project_name'];
                $data[$k]['order_sn'] = $v['order_sn'];
                $data[$k]['create_time'] = $v['create_time'];
                if ($v['status'] == 2) {
                    $status = '已成功';
                } elseif ($v['status'] == 1) {
                    $status = '进行中';
                } elseif ($v['status'] == 0) {
                    $status = '未成功';
                } else {
                    $status = '其他状态';
                }
                if ($v['cash_payment_status'] == 2) {
                    $cash_payment_status = '已失败';
                } elseif ($v['cash_payment_status'] == 1) {
                    $cash_payment_status = '已成功';
                } elseif ($v['cash_payment_status'] == 0) {
                    $cash_payment_status = '待处理';
                } else {
                    $cash_payment_status = '其他状态';
                }
                $data[$k]['status'] = $status;
                $data[$k]['cash_payment_status'] = $cash_payment_status;
                $data[$k]['cash_payment_remark'] = $v['cash_payment_remark'];
                $data[$k]['cash_payment_money'] = 1;

            }

            ToPHPEXECL($tableHeader, $data, '支持订单');
        }

        $dataList = $orModel->field('a.*,b.username,b.mobile,c.project_name')
            ->alias('a')
            ->join('tf_member b', 'a.uid=b.id', 'LEFT')
            ->join('tf_project c', 'a.project_id=c.id', 'LEFT')
            ->where($where)
            ->order($order)
            ->paginate('', false, page_param());
        $ProjectList = $pModel->field('id,project_name')->select();
        if ($dataList) {
            foreach ($dataList as $k => $v) {
                $dataList[$k]['cash_payment_money'] = floor($v['money'] * 0.2);

            }
        }
        $this->assign('cash_payment_status',input('get.cash_payment_status'));
        $this->assign('ProjectList', $ProjectList);
        $this->assign('dataList', $dataList);
        return $this->fetch();
    }

    //订单兑付
    public function duifu($id) {
        $orderClass = new Order();
        $YunClass = new Yunst();
        $memberClass = new Members();
        $orderPaymentClass = new OrderPayment();
        $orderData = $orderClass->where(['id' => $id])->find();


        $bizUserId = $memberClass->where(['id' => $orderData['uid']])->value('bizUserId');
        $orderSn = 'jiesuan'.$bizUserId.time();
        $aMoney = floor($orderData['money'] * 0.2);
        $new_order = [
            'order_sn' => $orderSn,
            'money'	=> $aMoney,
        ];
        if ($orderData['cash_payment_status'] != 0) {
            return ajaxReturn('该笔兑付订单已操作，请勿重复操作。');
        }
        $orderClass->where(['id'=>$id])->update(['cash_payment_status'=>2]);
        $new_message = $YunClass->PingTaiZhuanZhang($bizUserId,$new_order);
        if ($new_message['status'] != 'OK') {
            $orderClass->where(['id'=>$id])->update(['cash_payment_remark'=>$new_message['message'],'cash_payment_status'=>2]);
            return ajaxReturn('兑付失败');
        } else {
            $money = $memberClass->where(['id'=>$orderData['uid']])->value('money');
            $new_money = $money + $aMoney;
            $memberClass->where(['id'=>$orderData['uid']])->update(['money'=>$new_money]);
            $orderClass->where(['id'=>$id])->update(['cash_payment_status'=>1]);
            $logModel = new Putlog();
            $log = [
                'uid' => $orderData['uid'],
                'money' => $aMoney,
                'type'	=> 4, //结算
                'order'	=> 'OD'.create_order(),
                'status' => 1,
                'crate_time' => time()
            ];
            $logModel->allowField(true)->save($log);
            //计算收益
            $return_money = floor($aMoney-$orderData['money']);
            TobeNotice($orderData['uid'],'结算通知','尊敬的会员：您好！我司已针对《伏妖天师》项目进行回款，请您前往账户余额查看结算结果，谢谢支持！若有任何疑问请致电好融艺官方客服：400—605—9006。');
            return ajaxReturn('兑付成功');
        }
    }

    //查用户
    public function cha() {
        $YunClass = new Yunst();
        $bizUserId = 'hry13345429525';
        $new_message = $YunClass->Balance($bizUserId);
        print_r($new_message);exit;
    }



    //团队关系处理
    public function caca() {
        //根据订单查询
        $order_model = new Order();
        $data = $order_model->where(['status'=>[1,2,3],'rights_state'=>2])->select();
        echo '<pre/>';print_r($data);exit;

    }









}
